package visiopuce.graph;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class ToolTipsDialog extends Dialog {
	private String browserString;

	private int counter = 0;
	private int maxSeconds;

	private Browser browser;

	public ToolTipsDialog(Shell parentShell, String browserString) {
		super(parentShell);
		this.maxSeconds = 5;
		setShellStyle(SWT.NO_TRIM | SWT.ON_TOP | SWT.MODELESS | SWT.TOOL);
		this.browserString = browserString;
		setBlockOnOpen(false);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		String[] txts = browserString.split("<br/>");
		int max = 0;
		boolean une = false;
		for (String string : txts) {

			if (une) {
				if (string.length() > max) {
					max = string.length();
				}
			}
			une = true;
		}
		Composite composite = (Composite) super.createDialogArea(parent);
		final Display display = composite.getShell().getDisplay();
		GridLayout layout = new GridLayout(1, false);
		composite.setLayout(layout);

		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.widthHint = Math.max (200, max * 10);
		data.heightHint = Math.max (100,txts.length * 25);
		composite.setLayoutData(data);

		browser = new Browser(composite, SWT.NONE);
		browser.setText(browserString);
		GridData data2 = new GridData(SWT.FILL, SWT.FILL, true, true);
		data2.widthHint =  Math.max (200,max * 10);
		data2.heightHint = Math.max (100,txts.length * 25);
		browser.setLayoutData(data2);
		final Runnable timer = new Runnable() {
			public void run() {
				{
					if (!browser.isDisposed()) {
						counter++;
						if (counter <= maxSeconds) {
							display.timerExec(1000, this);
						} else {
							ToolTipsDialog.this.close();
						}
					}
				}
			}
		};
		display.timerExec(0, timer);
		return composite;
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("");
	}

	public String getText() {
		return browserString;
	}

	@Override
	protected Control createButtonBar(Composite parent) {
		return parent;
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
	}
}
